package com.bah.tract.client.ui;

import java.awt.Image;
import java.awt.PopupMenu;
import java.awt.TrayIcon;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Date;

import com.bah.tract.client.Timer;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

@Singleton
public class TRACTTrayIcon extends TrayIcon implements Timer {

	private final class IconMouseMotionListener implements MouseMotionListener {
		@Override
		public void mouseDragged(final MouseEvent e) {

		}

		@Override
		public void mouseMoved(final MouseEvent e) {
			if (mRunning) {
				final long now = new Date().getTime();
				// Approximate difference in minutes
				final double difference = Math
						.floor((now - mStart) / 60000.0);
				if (difference < 60) { // just minutes
					TRACTTrayIcon.this.setToolTip("Timing for "
							+ (int) difference + " min.");

				} else {
					// hours and minutes
					final double hours = Math.floor((difference / 60));
					final double minutes = difference % 60;
					TRACTTrayIcon.this.setToolTip("Timing for "
							+ (int) hours + " hrs " + (int) minutes
							+ " min.");
				}

			} else {
				TRACTTrayIcon.this.setToolTip("No active task.");
			}
		}
	}

	private final Image pauseImage;
	private final Image playImage;
	private boolean mRunning = false;
	private long mStart;

	@Inject
	TRACTTrayIcon(final MouseListener mouseListener,
			@Named("defaultImage") final Image icon,
			@Named("playImage") final Image playImage,
			@Named("pauseImage") final Image pauseImage, final PopupMenu menu) {
		super(icon, "TRACT", menu);
		this.pauseImage = pauseImage;
		this.playImage = playImage;
		setImageAutoSize(true);
		addMouseListener(mouseListener);
		addMouseMotionListener(new IconMouseMotionListener());
	}

	@Override
	public void setState(final boolean running) {
		mRunning = running;
		if (mRunning) {
			setImage(playImage);
			mStart = new Date().getTime();
		} else {
			mStart = 0;
			setImage(pauseImage);
		}
	}

	@Override
	public void toggle() {
		setState(!mRunning);
	}

}
